
#include <stdio.h>      // needed on Linux system
#include <unistd.h>     // for getopt
#include <iostream>
#include "tiny-parser.tab.h"
#include "TreeNode.h"
using namespace std;



int current_lineno = 1;
char *curr_filename = "<stdin>"; // this name is arbitrary
FILE *fin;   // This is the file pointer from which the lexer reads its input.
FILE *fout; //输出的文件
extern int yylex();



std::vector<std::string> string_table;//符号表

string token_to_string(int token){
	switch(token){
		case IF_T:
			return "IF";
		case THEN:
			return "THEN";
		case ELSE:
			return "ELSE";
		case END:
			return "END";
		case UNTIL:
			return "UNTIL";
		case READ:
			return "READ";
		case WRITE:
			return "WRITE";
		case NUM:
			return "NUMBER";
		case ASSIGN:
			return "ASSIGN";
		case EQ:
			return "EQ";
		case LT:
			return "GT";
		case PLUS:
			return "PLUS";
		case MINUS:
			return "MINUS";
		case TIMES:
			return "TIMES";
		case OVER:
			return "OVER";
		case LPAREN:
			return "LPAREN";
		case RPAREN:
			return "RPAREN";
		case ID:
			return "ID";
		case SEMI:
			return "SEMI";
		case ERROR:
			return "ERROR";
		case EOF:
			return "EOF";
		default:
			return "UNKNOWN";

	}
}
// defined in utilities.cc
void dump_cool_token(ostream& out, int lineno, int token, char* yylval){
	if(token==ID)
    	out<<lineno<<" "<<token_to_string(token)<<" "<<yylval<<endl;
	else if(token==NUM)
		out<<lineno<<" "<<token_to_string(token)<<" "<<yylval<<endl;
	else
		out<<lineno<<" "<<token_to_string(token)<<endl;
};

extern int yyparse(void);

int yywrap() {
    return 0;  // 默认行为：告诉解析器已经到达输入结尾
}

extern char *yytext;

void exp3(char **argv){
	int token;
	fin = fopen(argv[1], "r");
	if (fin == NULL) {
	cerr << "Could not open input file " << argv[1] << endl;
	exit(1);
	}
	cout << "#name \"" << argv[1] << "\"" << endl;
	while ((token = yylex()) != 0) {
		dump_cool_token(cout, current_lineno, token, yytext);
	}
	fclose(fin);
}

TreeNode* root;

int main(int argc, char** argv) {
	fin=fopen(argv[1],"r");
	if(fin==NULL){
		cerr<<"Could not open input file "<<argv[1]<<endl;
		exit(1);
	}
	cout<<"#name \""<<argv[1]<<"\""<<endl;

    // 调用 yyparse() 开始解析
    int result = yyparse();

    // 检查解析结果
    if (result == 0) {
        printf("Parsing successful!\n");
    } else {
        printf("Parsing failed.\n");
    }

    // 关闭输入流
    fclose(fin);
	root->show_all_info();

	//设置输出的文件
	char *file_output_name=new char(strlen(argv[1])+strlen(".vm")+1);
	strcpy(file_output_name,argv[1]);
	strcat(file_output_name,".vm");
	fout=fopen(file_output_name,"w");
	if(fout==NULL){
		cerr<<"Could not open output file "<<argv[2]<<endl;
		exit(1);
	}
	//生成代码
	root->generate_code();
	//关闭输出流
	fclose(fout);

	return 0;
}



